// lib/auth.js
import {cookies} from "next/headers";
import {jwtVerify, SignJWT} from "jose";
import {cache} from 'react'

const JWT_COOKIE = 'sessionToken'
const JWT_DURATION = 14 * 24 * 60 * 60 * 1000 // 14天
const JWT_SECRET = new TextEncoder().encode(process.env.JWT_SECRET)

// 每个页面最多执行一次, 缓存
const decodedSessionToken = cache(async (sessionToken) => {
    try {
        // navbar用到了, 会重复执行两次(layout+page)
        const {payload} = await jwtVerify(sessionToken, JWT_SECRET)
        return payload
    } catch (err) {
        // 如果客户端篡改了cookie, 这里就会报错, 因为jwt解析错误
        console.warn('Invalid JWT', err)
    }
})

export function getUserFromSession() {
    const sessionToken = cookies().get(JWT_COOKIE)?.value
    if (sessionToken) {
        return decodedSessionToken(sessionToken)
    }
}

export function deleteSessionCookie() {
    cookies().delete(JWT_COOKIE)
}

export async function setSessionCookie({id, email, name, desc}) {
    const expirationTime = new Date(Date.now() + JWT_DURATION)
    const sessionToken = await new SignJWT({id, email, name, desc})
        .setProtectedHeader({alg: 'HS256'}) // alg 加密算法
        .setExpirationTime(expirationTime) // 过期时间
        .sign(JWT_SECRET)
    cookies().set(JWT_COOKIE, sessionToken, {
        expires: expirationTime,
        httpOnly: true,
        sameSite: 'lax'
    })
}